import React, { useState, useRef, useEffect } from 'react';
import styles from './ChatPage.module.css';
import mammoth from 'mammoth';

interface Message {
  id: number;
  sender: 'user' | 'bot';
  content: string;
  timestamp: Date;
  type: 'text' | 'word-preview';
  wordPreview?: {
    title: string;
    htmlContent: string;
  };
}

interface ChatPageProps {
  onPageChange?: (page: string) => void;
}

const ChatPage: React.FC<ChatPageProps> = ({ onPageChange }) => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: 1,
      sender: 'bot',
      content: '您好！我是您的法律助手，有什么可以帮助您的吗？',
      timestamp: new Date(),
      type: 'text'
    },
    {
      id: 2,
      sender: 'user',
      content: '我想咨询一下房屋买卖合同纠纷的问题',
      timestamp: new Date(),
      type: 'text'
    }
  ]);
  
  const [inputValue, setInputValue] = useState('');
  const [isLoadingDoc, setIsLoadingDoc] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const loadWordDocument = async () => {
    setIsLoadingDoc(true);
    try {
      const response = await fetch('/1.3版本营销智能体方案设计20250814-v1.2.docx');
      const arrayBuffer = await response.arrayBuffer();
      
      // 使用mammoth.js转换docx为HTML
      const result = await mammoth.convertToHtml({ arrayBuffer });
      
      const wordMessage: Message = {
        id: Date.now(),
        sender: 'bot',
        content: '关于房屋买卖合同纠纷，我可以为您提供一些基本的法律信息和模板。这里有一份房屋买卖合同纠纷的民事起诉状实例，您可以参考一下：',
        timestamp: new Date(),
        type: 'word-preview',
        wordPreview: {
          title: '房屋买卖合同纠纷民事起诉状实例',
          htmlContent: result.value
        }
      };
      
      setMessages(prev => [...prev, wordMessage]);
      
      // 添加后续对话
      setTimeout(() => {
        const followUpMessage: Message = {
          id: Date.now() + 1,
          sender: 'bot',
          content: '这份起诉状模板包含了基本的格式和要素。您可以根据自己的具体情况进行修改。请问您遇到的具体纠纷情况是什么呢？我可以为您提供更有针对性的建议。',
          timestamp: new Date(),
          type: 'text'
        };
        setMessages(prev => [...prev, followUpMessage]);
      }, 2000);
      
    } catch (error) {
      console.error('读取Word文档失败:', error);
      // 如果读取失败，使用备用内容
      const fallbackMessage: Message = {
        id: Date.now(),
        sender: 'bot',
        content: '抱歉，无法读取文档内容。但是我可以为您提供基本的房屋买卖合同纠纷处理建议...',
        timestamp: new Date(),
        type: 'text'
      };
      setMessages(prev => [...prev, fallbackMessage]);
    } finally {
      setIsLoadingDoc(false);
    }
  };

  const handleSendMessage = () => {
    if (inputValue.trim() === '') return;

    const newMessage: Message = {
      id: Date.now(),
      sender: 'user',
      content: inputValue,
      timestamp: new Date(),
      type: 'text'
    };

    setMessages(prev => [...prev, newMessage]);
    setInputValue('');

    // 模拟机器人回复
    setTimeout(() => {
      const botReply: Message = {
        id: Date.now() + 1,
        sender: 'bot',
        content: '感谢您的咨询。基于您描述的情况，建议您先与对方协商解决，如协商不成可以寻求法律援助或向法院起诉维权。',
        timestamp: new Date(),
        type: 'text'
      };
      setMessages(prev => [...prev, botReply]);
    }, 1000);
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const formatTimestamp = (timestamp: Date) => {
    return timestamp.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  };

  // 自动加载Word文档
  useEffect(() => {
    if (messages.length === 2) { // 只在初始两条消息后加载
      setTimeout(() => {
        loadWordDocument();
      }, 1500);
    }
  }, [messages.length]);

  return (
    <div className={styles.chatPage}>
      <div className={styles.chatHeader}>
        <h2>💬 法律咨询助手</h2>
        <p>专业法律咨询，问题快速解答</p>
      </div>
      
      <div className={styles.chatContainer}>
        <div className={styles.messagesContainer}>
          {messages.map((message) => (
            <div 
              key={message.id} 
              className={`${styles.message} ${message.sender === 'user' ? styles.userMessage : styles.botMessage}`}
            >
              <div className={styles.messageContent}>
                <div className={styles.messageHeader}>
                  <span className={styles.sender}>
                    {message.sender === 'user' ? '🙋‍♂️ 您' : '⚖️ 法律助手'}
                  </span>
                  <span className={styles.timestamp}>
                    {formatTimestamp(message.timestamp)}
                  </span>
                </div>
                
                <div className={styles.messageText}>
                  {message.content}
                </div>
                
                {message.type === 'word-preview' && message.wordPreview && (
                  <div className={styles.wordPreview}>
                    <div className={styles.wordPreviewHeader}>
                      <span className={styles.wordIcon}>📄</span>
                      <span className={styles.wordTitle}>{message.wordPreview.title}</span>
                      <button 
                        className={styles.viewButton}
                        onClick={() => {
                          // 在新窗口中打开Word文档预览
                          const newWindow = window.open('', '_blank');
                          if (newWindow) {
                            newWindow.document.write(`
                              <html>
                                <head>
                                  <title>${message.wordPreview!.title}</title>
                                  <style>
                                    body { 
                                      font-family: "Microsoft YaHei", Arial, sans-serif; 
                                      line-height: 1.6; 
                                      margin: 40px; 
                                      background-color: #f5f5f5;
                                    }
                                    .document {
                                      background: white;
                                      padding: 40px;
                                      border-radius: 8px;
                                      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                                      max-width: 800px;
                                      margin: 0 auto;
                                    }
                                    h1 { 
                                      text-align: center; 
                                      color: #333; 
                                      border-bottom: 2px solid #007acc;
                                      padding-bottom: 10px;
                                    }
                                    .content { 
                                      color: #555; 
                                      margin-top: 20px;
                                    }
                                    .content p {
                                      margin-bottom: 10px;
                                    }
                                    .content h2, .content h3 {
                                      margin-top: 20px;
                                      margin-bottom: 10px;
                                    }
                                    .content ul, .content ol {
                                      margin-left: 20px;
                                    }
                                  </style>
                                </head>
                                <body>
                                  <div class="document">
                                    <h1>${message.wordPreview!.title}</h1>
                                    <div class="content">${message.wordPreview!.htmlContent}</div>
                                  </div>
                                </body>
                              </html>
                            `);
                            newWindow.document.close();
                          }
                        }}
                      >
                        查看详情
                      </button>
                    </div>
                    <div 
                      className={styles.wordPreviewContent}
                      dangerouslySetInnerHTML={{ 
                        __html: message.wordPreview.htmlContent 
                      }}
                    />
                  </div>
                )}
              </div>
            </div>
          ))}
          
          {isLoadingDoc && (
            <div className={styles.loadingMessage}>
              <div className={styles.loadingSpinner}></div>
              <span>正在加载文档内容...</span>
            </div>
          )}
          
          <div ref={messagesEndRef} />
        </div>
        
        <div className={styles.inputContainer}>
          <textarea
            className={styles.messageInput}
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="请输入您的法律问题..."
            rows={2}
          />
          <button 
            className={styles.sendButton}
            onClick={handleSendMessage}
            disabled={inputValue.trim() === ''}
          >
            发送
          </button>
        </div>
      </div>
    </div>
  );
};

export default ChatPage;